package withdraw

import (
	"context"
	"fmt"

	userrpc2 "gitee.com/liuxuezhan/ar-platform/rpc-client/userServiceClient/userrpc"

	"gitee.com/liuxuezhan/ar-platform/assets-api/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/assets-api/internal/types"
	"gitee.com/liuxuezhan/ar-platform/assets-api/pkg/xerrors"
	"gitee.com/liuxuezhan/ar-platform/base-common/headInfo"
	"gitee.com/liuxuezhan/ar-platform/base-common/pkg/xcode"
	"gitee.com/liuxuezhan/ar-platform/base-common/tool/wlog"
	"gitee.com/liuxuezhan/ar-platform/rpc-client/assetsClient/rpc"
	"github.com/zeromicro/go-zero/core/logx"
)

type WithdrawLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// c端用户提现页面--提现
func NewWithdrawLogic(ctx context.Context, svcCtx *svc.ServiceContext) *WithdrawLogic {
	return &WithdrawLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *WithdrawLogic) Withdraw(req *types.WithdrawReq) (resp *types.WithdrawRes, err error) {
	UserId := headInfo.GetTokenUid(l.ctx)
	if UserId == 0 {
		return nil, xerrors.UserTokenInvalid
	}

	rpc_req := &rpc.UserWithDrawReq{
		UserId:                UserId,
		Amount:                req.Amount,
		WithdrawTypeId:        req.WithdrawTypeId,
		WithdrawUserChannelId: req.WithdrawUserChannelId,
	}

	userGroupInfoRe := &userrpc2.UserGroupInfoRequest{UserId: UserId}
	userResult, err := l.svcCtx.UserRpc.UserGetGroupInfo(l.ctx, userGroupInfoRe)
	if err != nil {
		logx.Error(fmt.Sprintf("WithdrawLogic:Withdraw:UserGetGroupInfo, %v", err))
		return nil, xcode.New(500, "system getGroupInfo error")
	} else if perm := userResult.Data.Perms; perm != nil && !perm.Cash {
		return nil, xcode.New(500, "no  permission")
	}

	// 发送请求
	rpc_resp, err := l.svcCtx.AssetsRpc.PayWithdraw.Withdraw(l.ctx, rpc_req)
	if err != nil {
		wlog.Handle.Errorf(l.ctx, "Call ModifyVipLevelInfos error: %v", err)
		return nil, err
	}

	// 处理请求返回的结果
	// 解析、组合数据
	resp = &types.WithdrawRes{
		OrderNo: rpc_resp.Data.OrderNo,
	}
	return
}
